package model

import (
	"fmt"
	"goWeb/testSql/utils"
)

type User struct {
	Id    int
	Name  string
	Email string
}

func (this *User) AddUser() error {
	sqlString := "insert into users(Id,Name,Email) values(?,?,?)"

	stmt, err := utils.Db.Prepare(sqlString)
	if err != nil {
		fmt.Println("预编译出错，err=", err)
		return err
	}
	_, err = stmt.Exec(1, "kevin", "kevin@qq.com")
	if err != nil {
		fmt.Println("插入数据出错，err=", err)
		return err
	}
	return nil
}

func (this *User) AddUser2() error {
	sqlString := "insert into users(Id,Name,Email) values(?,?,?)"
	_, err := utils.Db.Exec(sqlString, 2, "renren", "5145@qq.com")
	if err != nil {
		fmt.Println("直接插入数据出错，err=", err)
		return err
	}
	return nil
}

func (this *User) GetUserById() (user *User, err error) {
	sqlString := "select Id,Name,Email from users where Id=?"
	row := utils.Db.QueryRow(sqlString, this.Id)
	var Id int
	var Name, Email string
	err = row.Scan(&Id, &Name, &Email)
	user = &User{
		Id:    Id,
		Name:  Name,
		Email: Email,
	}
	return user, err
}

func (this *User) GetUsers() (users []*User, err error) {
	sqlString := "select Id,Name,Email from users"
	rows, err := utils.Db.Query(sqlString)
	if err != nil {
		return nil, err
	}
	for rows.Next() {
		var Id int
		var Name, Email string
		err = rows.Scan(&Id, &Name, &Email)
		user := &User{
			Id:    Id,
			Name:  Name,
			Email: Email,
		}
		users = append(users, user)
	}
	return users, nil
}
